# -*- coding: UTF-8 -*-
"""
@auth:buxiangjie
@date:2022/8/31 16:38
@describe: 获取数据
"""

from app.db.get_sql_data import GetSqlData
from app.log.ulog import logger_


class Statistics(GetSqlData):

	def __init__(self, run_time):
		self.run_time = run_time

	def daily_count(self):
		# 判断是否存在数据
		def _is_exist(script="all") -> bool:
			sql = f"""
				select * from daily_total_situation where run_date='{self.run_time}'
				and script='{script}';
			"""
			is_exist = self.exec_select("test", sql, "statistics")
			return True if is_exist else False

		def _all():
			sql = f"""
						SELECT if(count(1) > 0, count(1), 0) AS all_num
						, ifnull(sum(if(status = 'passed', 1, 0)), 0) AS pass_num
						, ifnull(sum(if(status = 'failed', 1, 0)), 0) AS fail_num
						, ifnull(sum(if(status = 'skiped', 1, 0)), 0) AS skip_num
					FROM runcase_detail
					WHERE run_time = '{self.run_time}';
					"""
			res = self.exec_select("test", sql, "statistics")[0]

			if _is_exist() is False:
				sql3 = f"""
					insert into daily_total_situation(all_num,pass_num,fail_num,skip_num,run_date,script) values (
					{res["all_num"]},{res["pass_num"]},
					{res["fail_num"]},{res["skip_num"]},
					'{self.run_time}','all');
				"""
				self.exec_update("test", sql3, "statistics")
			else:
				sql3 = f"""
					update daily_total_situation set
					all_num={res["all_num"]},pass_num={res["pass_num"]},
					fail_num={res["fail_num"]},skip_num={res["skip_num"]},
					update_time=CURRENT_TIME
					where run_date='{self.run_time}' and script='all';
				"""
				self.exec_update("test", sql3, "statistics")

		def _every_script():
			sql = f"""
						SELECT script,if(count(1) > 0, count(1), 0) AS all_num
						, ifnull(sum(if(status = 'passed', 1, 0)), 0) AS pass_num
						, ifnull(sum(if(status = 'failed', 1, 0)), 0) AS fail_num
						, ifnull(sum(if(status = 'skiped', 1, 0)), 0) AS skip_num
					FROM runcase_detail
					WHERE run_time = '{self.run_time}'
					group by script;
					"""
			res = self.exec_select("test", sql, "statistics")

			if res is None:
				logger_.warning("昨日无数据")
			else:
				for scr in res:
					if _is_exist(scr["script"]) is False:
						sql3 = f"""
							insert into daily_total_situation(all_num,pass_num,fail_num,skip_num,run_date,script) values (
							{scr["all_num"]},{scr["pass_num"]},
							{scr["fail_num"]},{scr["skip_num"]},
							'{self.run_time}','{scr["script"]}');
						"""
						self.exec_update("test", sql3, "statistics")
					else:
						sql3 = f"""
							update daily_total_situation set
							all_num={scr["all_num"]},pass_num={scr["pass_num"]},
							fail_num={scr["fail_num"]},skip_num={scr["skip_num"]},
							update_time=CURRENT_TIME
							where run_date='{self.run_time}' and script='{scr["script"]}';
						"""
						self.exec_update("test", sql3, "statistics")

		_all()
		_every_script()
